package com.zwcl.gdw.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserVehicleVerifyUtil {

    public static String send(String url, String content, String method, String methodWithClient, String authorityCode) throws Exception
    {
        //创建http连接
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建http响应
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;

        int messageStatus = 0;

        try {

            String timeMill = getTimeMillStr();
            //创建post请求
            HttpEntity httpEntity = getHttpEntity(content, method, methodWithClient, timeMill);

            //生成内容的hash值
            String md5 = MD5.encryption(content);

            //创建http请求的配置文件，设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000)
                    .build();

            HttpPost httpPost = getHttpPost(url, authorityCode, timeMill, httpEntity, md5, requestConfig);

            //发送请求
            httpResponse = httpClient.execute(httpPost);
            //接受响应实体
            HttpEntity responseEntity = httpResponse.getEntity();
            //查看响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            //读取响应实体中的流
            reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String str;
            while ((str = reader.readLine()) != null) {
                buffer.append(str);
            }

            return buffer.toString();

        } finally {
            if(reader != null){
                reader.close();
            }
            httpClient.close();
            if (httpResponse != null) {
                httpResponse.close();
            }
        }

    }

    private static HttpPost getHttpPost(String url, String authorityCode, String timeMill, HttpEntity httpEntity, String md5, RequestConfig requestConfig) {
        HttpPost httpPost = new HttpPost(
                url+ timeMill + "@_@json");
        //设置请求配置
        httpPost.setConfig(requestConfig);
        //设置请求实体到httppost上
        httpPost.setEntity(httpEntity);

        //设置请求头
        httpPost.addHeader("binfile-md5", md5);
        httpPost.addHeader("binfile-auth", authorityCode);
        httpPost.addHeader("binfile-gzip", String.valueOf(true));
        return httpPost;
    }

    private static HttpEntity getHttpEntity(String content, String method, String methodWithCode, String timeMill) throws UnsupportedEncodingException {
        //创建请求实体构造器
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);


        byte[] contentB = content.getBytes("UTF-8");
        //增加二进制内容
        multipartEntityBuilder.addBinaryBody("binFile", contentB, ContentType.DEFAULT_BINARY,
                method + timeMill + ".json");
        //增加文本内容
        multipartEntityBuilder.addTextBody("filename", methodWithCode + timeMill + ".json");
        //构造请求实体
        return multipartEntityBuilder.build();
    }


    private static String getTimeMillStr()
    {
        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    }

    /**
     *
     * @param service
     * @param subService
     * @param client
     * @param code
     * @return
     */
    public static List<String> prepare(String service, String subService, String client, String code){
        List<String> result = new ArrayList<String>();

        String templateUrl = "https://dts.txffp.com/tts/app/common/binapi/{0}_{1}_REQ_";
        String templateMethod = "{0}_{1}_REQ_";
        String templateMethodWithCode = "{0}}_{1}_{2}_REQ_";
        String templateAuthCode = "{0}_{1}";

        String url = MessageFormat.format(templateUrl,service,subService);
        String method = MessageFormat.format(templateMethod, service,subService);
        String methodWithclient = MessageFormat.format(templateMethodWithCode, service,subService,client);
        String authCode = MessageFormat.format(templateAuthCode, client,code);

        result.add(url);
        result.add(method);
        result.add(methodWithclient);
        result.add(authCode);

        return result;
    }

    public static void main(String[] args) throws Exception {

        String plateNo = "车牌号";
        String idNum = "身份证号";
        String userName = "姓名";

        //前两个参数是固定的，后两个参数是行云提供的账户和授权码。临时写成字符串传入，最好改造一下
        String service = "ETCUSER";//固定
        String subService = "USERVEHICLEVERIFY";//固定
        String client = "000042";//行云发放
        String code = "CBCC6ee1n0";//行云发放

        //内容自己构建
        String contentTemplate = "{\"plateNo\":\"{0}\",\"idNum\":\"{1}\",\"userName\":\"{2}\"}";
        String content = MessageFormat.format(contentTemplate, plateNo,idNum,userName);


        List<String> parameters = prepare(service,subService,client,code);
        String result = send(parameters.get(0),content,parameters.get(1),parameters.get(2),parameters.get(3));
        System.out.println(result);
    }

}
